'use strict'

const {logger} = require('ee-core/log')
const {getConfig} = require('ee-core/config')
const {getMainWindow} = require('ee-core/electron')
const {app: ElectronApp} = require('electron')
const {appService} = require('../service/app')
const {windowService} = require('../service/os/window')
const {preventTitleBarContextMenuFunc, registerWindowOpenHandler} = require('../service/os/browser')

class Lifecycle {

    /**
     * core app have been loaded
     */
    async ready() {
        logger.info('[lifecycle] ready')
        //当前渲染进程主窗口标识
        process.env.EE_WINDOW_KEY = 'main'
        process.env.EE_APP_VERSION = ElectronApp.getVersion()
    }

    /**
     * electron app ready
     */
    async electronAppReady() {
        logger.info('[lifecycle] electron-app-ready')
        //初始化应用的下载目录路径设置
        const appDownloadsPath = appService.appDownloadsPath
        if (appDownloadsPath != null) {
            if (appDownloadsPath !== ElectronApp.getPath('downloads')) {
                ElectronApp.setPath('downloads', appDownloadsPath)
            }
        } else {
            appService.appDownloadsPath = ElectronApp.getPath('downloads')
        }
        logger.info('[lifecycle] appDownloadsPath is initialize.')
        //多次启动时，聚焦主窗口。
        ElectronApp.on('second-instance', (event, commandLine, workingDirectory) => {
            const mainWin = getMainWindow()
            if (mainWin.isDestroyed()) {
                return
            }
            if (mainWin.isClosable()) {
                mainWin.show()
            }
            if (!mainWin.isFocused()) {
                mainWin.focus()
            }
            logger.info('[lifecycle] emit second-instance event main window focus.')
        })
    }

    /**
     * main window have been loaded
     */
    async windowReady() {
        logger.info('[lifecycle] window-ready')

        const mainWin = getMainWindow()

        //初始化主窗口字体大小
        mainWin.webContents.once('did-finish-load', () => {
            mainWin.webContents.setZoomFactor(appService.appZoomFactor)
            //注册主窗口内容ID
            windowService.registerWCid('main', mainWin.webContents.id)
        })
        mainWin.webContents.once('destroyed', () => {
            //窗口卸载时，卸载主窗口内容ID
            windowService.removeWCid('main')
        })
        //渲染进程崩溃时，卸载主窗口内容ID
        mainWin.webContents.once('render-process-gone', () => {
            windowService.removeWCid('main')
        })
        //阻止窗口标题栏右键默认上下文菜单
        preventTitleBarContextMenuFunc(mainWin, () => {
            logger.info('[lifecycle] system-context-menu be rejected.')
        })
        //注册网页<a target="_blank">标签和window.open拦截处理器
        registerWindowOpenHandler(mainWin)

        //初始化主窗口背景色
        mainWin.setBackgroundColor(appService.appBackgroundColor)
        //初始化窗口置顶状态
        mainWin.setAlwaysOnTop(!!appService.appMainPinned)
        //根据本地配置初始化窗口尺寸
        let appIsMaximized = appService.appMainIsMaximized
        if (appIsMaximized && !mainWin.isMaximized()) {
            mainWin.maximize()
        }
        if (!appIsMaximized && mainWin.isMaximized()) {
            mainWin.unmaximize()
        }
        //窗口延迟加载无白屏
        if (getConfig().windowsOption.show === false) {
            mainWin.once('ready-to-show', () => {
                mainWin.show()
                mainWin.focus()
            })
        }
    }

    /**
     * before app close
     */
    async beforeClose() {
        logger.info('[lifecycle] before-close')
    }
}

Lifecycle.toString = () => '[class Lifecycle]'

module.exports = {
    Lifecycle
}